package warehouse;

import entity.OrdersLocal;
import entity.OrdersLocalHome;
import excel.ExcelReportBuilder;
import helper.SimpleJSONArray;
import helper.SimpleJSONObject;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;
import javax.ejb.FinderException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import report.ReportData;
import report.ReportDataFactory;
import report.filter.CreationDateFilter;
import report.filter.CustomerFilter;
import report.filter.OrderStateFilter;
import report.filter.WarehouseFilter;

/**
 *
 * @author Oleh
 */
public class OrderReport extends HttpServlet {

    public static final String dateFromParameter = "dateFrom";
    public static final String dateToParameter = "dateTo";
    public static final String customerParameter = "customer";
    public static final String warehouseParameter = "warehouse";
    public static final String stateParameter = "state";
    public static final String startParameter = "start";
    public static final String quantityParameter = "quantity";
    public static final String actionParameter = "action";
    public static final String generateValue = "generate";
    public static final String exportValue = "export";
    public static final String idProperty = "id";
    public static final String stateProperty = "state";
    public static final String loginProperty = "login";
    public static final String createProperty = "create";
    public static final String warehouseProperty = "warehouse";
    public static final String totalProperty = "total";
    public static final String idColumn = "id_order";
    public static final String stateColumn = "id_order_state";
    public static final String createColumn = "creation_date";
    public static final String totalColumn = "total_cost";
    public static final String loginColumn = "id_customer";
    public static final String warehouseColumn = "id_warehouse";
    public static final String columnParameter = "column";
    public static final String directionParameter = "direction";
    public static final String upValue = "up";
    public static final String downValue = "down";
    public static final String desc = " DESC";
    public static final String fileProperty = "file";

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String dateFrom = request.getParameter(dateFromParameter);
        String dateTo = request.getParameter(dateToParameter);
        String customer = request.getParameter(customerParameter);
        String warehouse = request.getParameter(warehouseParameter);
        String state = request.getParameter(stateParameter);
        String start = request.getParameter(startParameter);
        String quantity = request.getParameter(quantityParameter);
        String action = request.getParameter(actionParameter);
        String column = request.getParameter(columnParameter);
        String direction = request.getParameter(directionParameter);

        System.out.println("action = " + action);
        System.out.println("dateFrom = " + dateFrom);
        System.out.println("dateTo = " + dateTo);
        System.out.println("customer = " + customer);
        System.out.println("warehouse = " + warehouse);
        System.out.println("state = " + state);
        System.out.println("start = " + start);
        System.out.println("quantity = " + quantity);
        System.out.println("column = " + column);
        System.out.println("direction = " + direction);

        ArrayList filters = new ArrayList();
        if ((dateFrom != null && !dateFrom.equals("")) || (dateTo != null && !dateTo.equals(""))) {
            filters.add(new CreationDateFilter(dateFrom, dateTo));
        }
        if (customer != null && !customer.equals("")) {
            filters.add(new CustomerFilter(customer));
        }
        if (warehouse != null && !warehouse.equals("")) {
            filters.add(new WarehouseFilter(warehouse));
        }
        if (state != null && !state.equals("")) {
            filters.add(new OrderStateFilter(state));
        }
        
        String orderBy = null;
        if (column != null && !column.equals("")) {
            orderBy = generateOrderBy(column, direction);
        }

        Integer startInt = (start != null && !start.equals("")) ? Integer.valueOf(start) : null;
        Integer quantityInt = (quantity != null && !quantity.equals("")) ? Integer.valueOf(quantity) : null;

        try {
            Context context = new InitialContext();
            OrdersLocalHome ordersHome = (OrdersLocalHome) context.lookup("java:comp/env/Orders");
            ArrayList report = new ArrayList();
            Collection reportCollection = ordersHome.findOrdersReport(filters, orderBy, startInt, quantityInt);
            for (Iterator iterator = reportCollection.iterator(); iterator.hasNext();) {
                OrdersLocal reportItem = (OrdersLocal) iterator.next();
                report.add(reportItem.getOrderReport());
            }
            if (generateValue.equals(action)) {
                SimpleJSONArray array = new SimpleJSONArray();
                for (int i = 0; i < report.size(); i++) {
                    SimpleJSONObject record = new SimpleJSONObject();
                    transfer.OrderReport current = (transfer.OrderReport) report.get(i);
                    record.addProperty(idProperty, current.idOrder.toString());
                    record.addProperty(stateProperty, current.orderState);
                    record.addProperty(loginProperty, current.login);
                    record.addProperty(warehouseProperty, current.nameWarehouse);
                    record.addProperty(createProperty, current.creationDate.toString());
                    record.addProperty(totalProperty, current.totalCost.toString());
                    array.addElement(record);
                }
                response.setContentType("application/json;charset=UTF-8");
                PrintWriter out = response.getWriter();
                out.print(array);
                out.flush();
                out.close();
            }
            if (exportValue.equals(action)) {
                ReportData reportData = ReportDataFactory.getReportData(report);
                if (!ExcelReportBuilder.configLoaded) {
                    Properties props = ExcelReportBuilder.loadProperties();
                    String reportFolder = getServletContext().getRealPath("")
                                    + File.separator + props.getProperty("SAVE_PATH");
                    props.setProperty("SAVE_PATH", reportFolder);
                    ExcelReportBuilder.saveProperties(props);
                }                       
                String file = ExcelReportBuilder.buildReport(reportData);
                System.out.println("file = " + file);
                SimpleJSONObject json = new SimpleJSONObject();
                String[] names = file.split("\\\\");
                file = names[names.length - 2] + "/" + names[names.length - 1];
                json.addProperty(fileProperty, file);
                response.setContentType("application/json;charset=UTF-8");
                PrintWriter out = response.getWriter();
                out.print(json);
                out.flush();
                out.close();
            }
        } catch (NamingException ex) {
            ex.printStackTrace();
        } catch (FinderException ex) {
            ex.printStackTrace();
        }
    }

    public static String generateOrderBy(String column, String direction) {
        String result = null;
        if (idProperty.equals(column)) {
            result = idColumn;
        }
        if (stateProperty.equals(column)) {
            result = stateColumn;
        }
        if (loginProperty.equals(column)) {
            result = loginColumn;
        }
        if (createProperty.equals(column)) {
            result = createColumn;
        }
        if (warehouseProperty.equals(column)) {
            result = warehouseColumn;
        }
        if (totalProperty.equals(column)) {
            result = totalColumn;
        }
        if (result == null) {
            return null;
        }
        if (downValue.equals(direction)) {
            result += desc;
        }
        return result;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
